package com.lu.servlet;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.lu.dao.impl.CommentDaoImpl;
import com.lu.entity.Comment;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

public class InsertOneCommentServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");

        resp.setContentType("text/html");
        PrintWriter out = resp.getWriter();

        int cnid = Integer.parseInt(req.getParameter("cnid"));
        String cauthor = req.getParameter("cauthor");
        String cip = req.getParameter("cip");
        String ccontent = req.getParameter("ccontent");

        Comment comment = new Comment(cnid, ccontent, cip, cauthor);
        int result = new CommentDaoImpl().insertOneComment(comment);
        if (result > 0) {
            List<Comment> commentList = new CommentDaoImpl().getSomeComments(cnid);
            Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd").create();
            String str = gson.toJson(commentList);
            out.print(str);
        }else{
            out.print("");
        }
        out.flush();
        out.close();
    }
}
